const COLORS = ['#FF4757', '#2ED573', '#1E90FF', '#FFA502', '#A45EFF'];
const GRID_SIZE = 8;

Page({
  data: {
    grid: [],
    score: 0,
    steps: 15,
    selected: null,
    gameOver: false,
    gridSize: 300 // 初始值，后续动态计算
  },

  onLoad() {
    this.initGrid(true);
  },

  onReady() {
    // 动态计算棋盘尺寸（参考网页64屏幕适配）
    const windowInfo = wx.getWindowInfo();
    const safeWidth = Math.min(windowInfo.windowWidth, windowInfo.windowHeight) - 40;
    this.setData({ gridSize: safeWidth });
  },

  // 核心初始化逻辑（参考网页3数据初始化）
  initGrid(initial = false) {
    let grid = [];
    for (let y = 0; y < GRID_SIZE; y++) {
      grid[y] = [];
      for (let x = 0; x < GRID_SIZE; x++) {
        let color;
        do {
          color = COLORS[Math.floor(Math.random() * COLORS.length)];
        } while (this.hasInitialConflict(grid, y, x, color));
        grid[y][x] = { x, y, color };
      }
    }
    this.setData({ grid }, () => {
      if(initial) this.cleanInitialMatches();
    });
  },

  hasInitialConflict(grid, y, x, color) {
    return (x >= 2 && grid[y][x-1].color === color && grid[y][x-2].color === color) ||
           (y >= 2 && grid[y-1][x].color === color && grid[y-2][x].color === color);
  },

  handleCellTap(e) {
    const { x, y } = e.currentTarget.dataset;
    const currentX = parseInt(x), currentY = parseInt(y);
    
    if (currentX >= GRID_SIZE || currentY >= GRID_SIZE) return;

    const selected = this.data.selected;
    if (!selected) {
      this.setData({ selected: { x: currentX, y: currentY } });
    } else {
      if (Math.abs(selected.x - currentX) + Math.abs(selected.y - currentY) === 1) {
        this.swapCells(selected, { x: currentX, y: currentY });
      }
      this.setData({ selected: null });
    }
  },

  swapCells(a, b) {
    const newGrid = this.data.grid.map(row => row.map(cell => ({...cell})));
    [newGrid[a.y][a.x], newGrid[b.y][b.x]] = [newGrid[b.y][b.x], newGrid[a.y][a.x]];
    
    this.setData({ grid: newGrid }, () => {
      const matches = this.checkMatches(newGrid);
      if (matches.size === 0) {
        setTimeout(() => this.revertSwap(a, b), 300);
      } else {
        this.handleClearMatches(newGrid, matches);
      }
    });
  },

  checkMatches(grid) {
    const matches = new Set();
    
    // 动态规划检测（参考网页20）
    grid.forEach((row, y) => {
      let count = 1;
      for (let x = 1; x <= GRID_SIZE; x++) {
        if (x < GRID_SIZE && row[x].color === row[x-1].color) {
          count++;
        } else {
          if (count >= 3) {
            for (let i = x - count; i < x; i++) {
              matches.add(`${y},${i}`);
            }
          }
          count = 1;
        }
      }
    });

    for (let x = 0; x < GRID_SIZE; x++) {
      let count = 1;
      for (let y = 1; y <= GRID_SIZE; y++) {
        if (y < GRID_SIZE && grid[y][x].color === grid[y-1][x].color) {
          count++;
        } else {
          if (count >= 3) {
            for (let i = y - count; i < y; i++) {
              matches.add(`${i},${x}`);
            }
          }
          count = 1;
        }
      }
    }
    
    return matches;
  },

  handleClearMatches(grid, matches) {
    const newGrid = grid.map((row, y) => 
      row.map((cell, x) => 
        matches.has(`${y},${x}`) ? {...cell, color: null} : cell
      )
    );
    
    this.setData({ 
      grid: newGrid,
      score: this.data.score + matches.size * 10,
      steps: this.data.steps - 1
    }, () => {
      setTimeout(() => this.refillGrid(), 500);
    });
  },

  refillGrid() {
    const newGrid = this.data.grid.map(row => [...row]);
    
    // 下落填充算法（参考网页20）
    for (let x = 0; x < GRID_SIZE; x++) {
      let ptr = GRID_SIZE - 1;
      for (let y = GRID_SIZE - 1; y >= 0; y--) {
        if (newGrid[y][x].color) {
          newGrid[ptr][x] = {...newGrid[y][x]};
          ptr--;
        }
      }
      for (let y = ptr; y >= 0; y--) {
        newGrid[y][x] = { 
          x, y, 
          color: COLORS[Math.random() * COLORS.length | 0] 
        };
      }
    }
    
    this.setData({ grid: newGrid });
  },

  revertSwap(a, b) {
    const grid = this.data.grid.map(row => [...row]);
    [grid[a.y][a.x], grid[b.y][b.x]] = [grid[b.y][b.x], grid[a.y][a.x]];
    this.setData({ grid });
  },

  onReady() {
    const windowInfo = wx.getWindowInfo();
    console.log('屏幕宽度:', windowInfo.windowWidth);
  }
});